package com.wondertek.poms.core.service.impl;

import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.core.service.IAdvanceModelSaleService;
import com.wondertek.poms.dao.po.AdvanceModelSale;
import com.wondertek.poms.dao.repo.IAdvanceModelSaleDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author evan0213
 * @description
 */
@Service
public class AdvanceModelSaleServiceImpl extends ServiceImpl<AdvanceModelSale, Long> implements IAdvanceModelSaleService {
	@Autowired
	private IAdvanceModelSaleDao iAdvanceModelSaleDao;

	@Override
	public AdvanceModelSale deleteLogic(Long id) {
		AdvanceModelSale advanceModelSale = jpaRepository.getOne(id);
		AdvanceModelSale.putTimeAndUser(advanceModelSale);
		advanceModelSale.setDel(Constants.DELETE_1);
		jpaRepository.save(advanceModelSale);
		return advanceModelSale;
	}

	@Override
	public AdvanceModelSale merge(AdvanceModelSale model) {
		return null;
	}

	/**
	 * @param entity 查询实体
	 * @param page   页码
	 * @param rows   条数
	 * @param order  排序列
	 * @param column asc/desc
	 * @return 分页对象
	 */
	public Page<AdvanceModelSale> findAll(AdvanceModelSale entity, int page, int rows, String order, String column) {
		Pageable pageable = getPageable(page - 1, rows, column, order);
		Specification<AdvanceModelSale> specification = getWhereClause(entity);
		return iAdvanceModelSaleDao.findAll(specification, pageable);
	}

	/**
	 * 构造分页条件
	 *
	 * @param advanceModelSale
	 * @return
	 */
	private Specification<AdvanceModelSale> getWhereClause(final AdvanceModelSale advanceModelSale) {
		return (Specification<AdvanceModelSale>) (root, query, cb) -> {
			List<Predicate> predicate = new ArrayList<>();
			if (StringUtils.isNotBlank(advanceModelSale.getAdvanceTradeName())) {
				predicate.add(cb.like(root.get("advanceTradeName"), "%" + advanceModelSale.getAdvanceTradeName() + "%"));
			}
			if (null != advanceModelSale.getAdvanceModel()) {
				predicate.add(cb.equal(root.get("advanceModel"), advanceModelSale.getAdvanceModel()));
			}
			predicate.add(cb.equal(root.get("del"), Constants.DELETE_0));
			Predicate[] pre = new Predicate[predicate.size()];
			return query.where(predicate.toArray(pre)).getRestriction();
		};
	}

	@Override
	public List<AdvanceModelSale> findAllByAdvanceTradeName(String advanceTradeName) {
		return iAdvanceModelSaleDao.findAllByAdvanceTradeName(advanceTradeName);
	}
}
